<template>
  <el-dropdown v-bind="$attrs" size="medium" trigger="click" @command="onClick">
    <template #default>
      <slot></slot>
    </template>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item v-for="item in dataList" :key="item.command" :command="item.command">
          {{ item.label }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue';

/**
 * 下拉菜单组件封装
 * @Author yuanyexu
 * @Date 2021-08-03
 */
export default defineComponent({
  name: 'DropdownMenu',
  props: {
    /**
     * 下拉菜单数据源集合
     * @type {object[]}
     */
    dataList: {
      type: Array as PropType<{ command: string; label: string; callback?: () => void }[]>,
      default: () => [],
    },
  },
  emits: ['command-click'],
  setup(props, ctx) {
    /**
     * 监听下拉菜单点击事件，执行回调函数，emit事件传参
     * @param {string} command 菜单点击项
     */
    const onClick = (command: string) => {
      const menu = props.dataList.find((item) => {
        return item.command === command;
      });

      if (menu?.callback) {
        menu.callback();
      }

      ctx.emit('command-click', command);
    };

    return {
      onClick,
    };
  },
});
</script>
